package com.gzyj.web.api;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzyj.data.common.PageData;
import com.gzyj.data.common.PageParam;
import com.gzyj.data.common.ResponseMsg;
import com.gzyj.data.web.cljk.*;
import com.gzyj.jtt808.utils.IntUtils;
import com.gzyj.pojo.gps.GzyjVideoHistory;
import com.gzyj.pojo.web.alarm.BaobiaoAlarmsummary;
import com.gzyj.pojo.web.gps.GzyjDaoluyunshuGps;
import com.gzyj.pojo.web.gps.GzyjStopHistory;
import com.gzyj.web.config.SysConfig;
import com.gzyj.web.mapper.alarm.BaobiaoAlarmsummaryMapper;
import com.gzyj.web.mapper.gps.GzyjDaoluyunshuGpsMapper;
import com.gzyj.web.mapper.gps.GzyjStopHistoryMapper;
import com.gzyj.web.mapper.gps.GzyjVideoHistoryMapper;
import com.gzyj.web.mapper.tpvdata.TpvehdataMapper;
import com.gzyj.web.service.CljkService;
import com.gzyj.web.service.MapFixService;
import com.gzyj.web.utils.DateUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.calcite.adapter.jdbc.JdbcSchema;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.stream.Collectors;


@RestController
@RequestMapping("api/cljk")
public class CljkApi {


    @Autowired
    private CljkService cljkService;

    @ApiOperation(value = "获取车辆组织列表", notes = "获取车辆组织列表")
    @PostMapping("/getCarOrgList")
    public ResponseMsg<CarTree> getCarOrgList(CljkCarSearchParam param) {

        return new ResponseMsg<>(200, "success", cljkService.buildDeptCarTree(param));

    }


    @Autowired
    private TpvehdataMapper tpvehdataMapper;

    @Autowired
    private MapFixService mapFixService;


    public List<VehPositionDataDTO> buildPositionDataList(List<HashMap<String, String>> dataList, int onlineTime) {
        List<VehPositionDataDTO> positionDataList = new ArrayList<>();
        onlineTime = onlineTime * SysConfig.minuteSec;
        for (HashMap<String, String> dataMap : dataList) {
            VehPositionDataDTO positionData = new VehPositionDataDTO();
            positionData.setVehId(dataMap.get("vehicleId"));
            positionData.setPlateNo(dataMap.get("plateNo"));
            positionData.setPlateColor(dataMap.get("plateColor"));
            positionData.setCompanyName(dataMap.get("depName"));
            positionData.setRunType(dataMap.get("yingyunleixing"));
            positionData.setTerminalId(dataMap.get("zongduanid"));
            positionData.setSimNum(dataMap.get("simNo"));
            positionData.setVideoChannelNum(StringUtils.isNotEmpty(dataMap.get("videoChannelNum")) ? Integer.valueOf(String.valueOf(dataMap.get("videoChannelNum"))) : 0);
            positionData.setAcc(String.valueOf(dataMap.get("acc")).equals("1") ? "开" : "关");
            positionData.setSignalNum("null".equals(String.valueOf(dataMap.get("wifisignal"))) ? "0" : String.valueOf(dataMap.get("wifisignal")));
            positionData.setSatelliteNum("null".equals(String.valueOf(dataMap.get("satellitelen"))) ? "0" : String.valueOf(dataMap.get("satellitelen")));
            String gpsTime = String.valueOf(dataMap.get("sendTime"));
            if ("".equals(gpsTime) || SysConfig.neverOnlineTime.equals(gpsTime)) {
                positionData.setOnlineType(SysConfig.neverOnlineMsg);
                positionData.setOnlineTypeNum(0);
            } else {
                int secs = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, gpsTime));
                positionData.setOnlineType((0 < secs && secs < onlineTime) ? SysConfig.onlineMsg : SysConfig.offLineMsg);
                positionData.setOnlineTypeNum((0 < secs && secs < onlineTime) ? 1 : 2);
            }
            positionData.setDirectionNum(Integer.valueOf(String.valueOf(dataMap.get("direction"))));
            positionData.setAlarmStatus(Integer.valueOf(String.valueOf(dataMap.get("alarmState"))));
            positionData.setAlarmType(String.valueOf(dataMap.get("alarmNote")));
            positionData.setGpsTime(gpsTime);
            positionData.setSpeed(String.valueOf(dataMap.get("velocity")));
            positionData.setDirection(getDirectionDescr(String.valueOf(dataMap.get("direction"))));
            positionData.setLocalStatus(Integer.valueOf(String.valueOf(dataMap.get("LocalFlag"))) == 1 ? "定位" : "不定位");
            positionData.setAltitude("");
            positionData.setLat(Double.valueOf(String.valueOf(dataMap.get("latitude"))));
            positionData.setLng(Double.valueOf(String.valueOf(dataMap.get("longitude"))));
            PointLatLng mapPoint = mapFixService.fix(positionData.getLat(), positionData.getLng(), "");
            positionData.setMaplat(mapPoint.getLat());
            positionData.setMaplng(mapPoint.getLng());
            positionData.setDriverName(dataMap.get("driverName"));

            if (dataMap.get("oil") != null) positionData.setOil(Integer.valueOf(String.valueOf(dataMap.get("oil"))));
            else positionData.setOil(0);
            if (dataMap.get("mileZongduan") != null)
                positionData.setMileZongduan(Integer.valueOf(String.valueOf(dataMap.get("mileZongduan"))));
            else positionData.setMileZongduan(0);
            if (dataMap.get("mileToday") != null)
                positionData.setMileToday(Double.valueOf(String.valueOf(dataMap.get("mileToday"))));
            else positionData.setMileToday(0d);
            if (dataMap.get("mileTotal") != null)
                positionData.setMileTotal(Double.valueOf(String.valueOf(dataMap.get("mileTotal"))));
            else positionData.setMileTotal(0d);

            String uploadTime = dataMap.get("uploadTime");

            String stopStrTime = "" + dataMap.get("stopTime");
            int stopTime = DateUtils.secStrToNowTime(stopStrTime);

            int secs = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, uploadTime));
            String stopTimes = secs > SysConfig.day7Sec ? ">7天" : secs > SysConfig.daySec ? ">1天" : DateUtils.secToTime(secs);
            boolean online = (0 < secs && secs < SysConfig.onlineTime * SysConfig.minuteSec) ? true : false;

            if (online) {

                if (Integer.valueOf(positionData.getSpeed()) > 1) {

                    int secsGps = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, gpsTime));
                    boolean isRun = (0 < secsGps && secsGps < SysConfig.onlineTime * SysConfig.minuteSec) ? true : false;
                    if (isRun) {
                        // gps时间在半小时内
                        positionData.setStatus(SysConfig.iruncar);
                    } else {
                        // gps时间在半小时以前
                        if (Integer.valueOf(String.valueOf(dataMap.get("acc"))) == 1) {
                            positionData.setStatus(SysConfig.istopcar);
                        } else {
                            positionData.setStatus(SysConfig.iflameoutcar);
                        }
                    }
                } else {


                    if (Integer.valueOf(String.valueOf(dataMap.get("acc"))) == 1) {

                        positionData.setStatus(SysConfig.istopcar);
                    } else {

                        positionData.setStatus(SysConfig.iflameoutcar);
                    }
                }
            } else {
                if ("".equals(uploadTime) || SysConfig.neverOnlineTime.equals(uploadTime)) {
                    positionData.setStatus(SysConfig.ineverOn);
                } else {

                    positionData.setStatus(SysConfig.iofflinecar);
                }
            }


            positionDataList.add(positionData);

        }
        return positionDataList;
    }

    public String getDirectionDescr(String directions) {
        String descr = "";
        int direction = Integer.valueOf(directions);
        if (direction == 0) {
            descr = "正北";
        } else if (direction == 90) {
            descr = "正东";
        } else if (direction == 180) {
            descr = "正南";
        } else if (direction == 270) {
            descr = "正西";
        } else if (direction == 45) {
            descr = "东北";
        } else if (direction == 135) {
            descr = "东南";
        } else if (direction == 225) {
            descr = "西南";
        } else if (direction == 315) {
            descr = "西北";
        } else if (direction < 90) {
            descr = "东偏北" + direction + "度";
        } else if (direction > 90 && direction < 180) {
            descr = "东偏南" + (direction - 90) + "度";
        } else if (direction > 180 && direction < 270) {
            descr = "西偏南" + (270 - direction) + "度";
        } else if (direction > 270 && direction < 360) {
            descr = "西偏北" + (direction - 270) + "度";
        }
        return descr;
    }


    @ApiOperation(value = "综合监控实时数据列表接口", notes = "综合监控实时数据列表接口")
    @PostMapping("/getCarPageList")
    public ResponseMsg<List<VehPositionDataDTO>> getCarPageList(VehicleLocationReq vehicleLocationReq) {
        List<VehPositionDataDTO> tpvehdataList = new ArrayList<>();
        if (vehicleLocationReq.getVehIds() != null && vehicleLocationReq.getVehIds().size() > 0) {
            tpvehdataList = buildPositionDataList(tpvehdataMapper.selectTpvehdataListByVehIds(vehicleLocationReq.getVehIds()), SysConfig.onlineTime * SysConfig.minuteSec);
        } else if (vehicleLocationReq.getDeptIds() != null && vehicleLocationReq.getDeptIds().length > 0) {
            tpvehdataList = buildPositionDataList(tpvehdataMapper.selectTpvehdataListByDeptIds(vehicleLocationReq.getDeptIds()), SysConfig.onlineTime * SysConfig.minuteSec);
        }

        return new ResponseMsg<>(200, "success", tpvehdataList);
    }

    @Autowired
    private BaobiaoAlarmsummaryMapper baobiaoAlarmsummaryMapper;

    @ApiOperation(value = "综合监控北斗报警数据列表接口", notes = "综合监控北斗报警数据列表接口")
    @PostMapping("/getMonitorAlarmList")
    public ResponseMsg<PageData<BaobiaoAlarmsummary>> getMonitorAlarmList(VehicleMonitorAlarmReq alarmReq) {

        Page<BaobiaoAlarmsummary> p = new Page<>(alarmReq.getPage(), alarmReq.getSize());
        QueryWrapper<BaobiaoAlarmsummary> w = new QueryWrapper<>();
        w.orderByDesc("BeginTime");
        if (StringUtils.isNotEmpty(alarmReq.getStartTime()) && StringUtils.isNotEmpty(alarmReq.getEndTime())) {
            w.between("BeginTime", alarmReq.getStartTime(), alarmReq.getEndTime());
        }

        Page<BaobiaoAlarmsummary> page = baobiaoAlarmsummaryMapper.selectPage(p, w);


        return new ResponseMsg<>(200, "success", new PageData<>(Long.valueOf(page.getTotal()).intValue(), page.getRecords()));
    }


    @Autowired
    protected ApplicationContext applicationContext;

    @ApiOperation(value = "综合监控主动安全报警数据列表接口", notes = "综合监控主动安全报警数据列表接口")
    @PostMapping("getMonitorSafeAlarmList")
    public ResponseMsg<PageData<VehSafeAlarmDataBO>> getMonitorSafeAlarmList(VehicleMonitorSafeAlarmReq param) {

        // 获取配置的数据源
        DynamicRoutingDataSource dataSource = applicationContext.getBean(DynamicRoutingDataSource.class);

        // 配置Calcite连接属性
        Properties info = new Properties();
        info.setProperty("lex", "JAVA");

        // 获取Calcite连接
        Connection connection = null;

        CalciteConnection calciteConnection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DriverManager.getConnection("jdbc:calcite:", info);
            calciteConnection = connection.unwrap(CalciteConnection.class);
            SchemaPlus rootSchema = calciteConnection.getRootSchema();

            DataSource mysqlDataSource = dataSource.getDataSource("mysql");
            // 添加MySQL数据源到Calcite模式
            JdbcSchema mysqlSchema = JdbcSchema.create(rootSchema, "db1", mysqlDataSource, null, "blade");
            rootSchema.add("db1", mysqlSchema);

            DataSource pgDataSource = dataSource.getDataSource("tidb");
            // 添加MySQL数据源到Calcite模式
            JdbcSchema pgSchema = JdbcSchema.create(rootSchema, "db2", pgDataSource, null, "gzyj_daoluyunshu");
            rootSchema.add("db2", pgSchema);

            //SQL语句
            String sql = " select b.id as vehId,b.cheliangpaizhao as vehNo,b.chepaiyanse as vehColor,b.shiyongxingzhi as shiyongxingzhi,b.dept_id as deptId,dept64.dept_name as deptName,a.FlagState as flagState,a.AlarmType as alarmType,a.Alarmlevel as level,a.Velocity as speed,a.High as high,a.Lat as lat, a.Lon as lng,a.GpsTime as gpsTime,a.AlarmNumber as alarmNumber,\'ADAS\' as alarmSource,a.driverName as driverName from db2.t_cmd0200_64 a join db1.anbiao_vehicle b on a.VehID = b.id left join db1.blade_dept dept64 on b.dept_id=dept64.id" + " union all " + " select b.id as vehId,b.cheliangpaizhao as vehNo,b.chepaiyanse as vehColor,b.shiyongxingzhi as shiyongxingzhi,b.dept_id as deptId,dept64.dept_name as deptName,a.FlagState as flagState,a.AlarmType as alarmType,a.Alarmlevel as level,a.Velocity as speed,a.High as high,a.Lat as lat, a.Lon as lng,a.GpsTime as gpsTime,a.AlarmNumber as alarmNumber,\'DMS\' as alarmSource,a.driverName as driverName from db2.t_cmd0200_65 a join db1.anbiao_vehicle b on a.VehID = b.id left join db1.blade_dept dept64 on b.dept_id=dept64.id" + " order by gpsTime desc limit ? offset ?";
            // 创建查询语句
            statement = calciteConnection.prepareStatement(sql);
            statement.setInt(1, param.getSize());
            statement.setInt(2, (param.getPage() - 1) * param.getSize());
            // 执行查询
            resultSet = statement.executeQuery();
            // 处理结果
            // 获取列数
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            List<VehSafeAlarmDataBO> list = new ArrayList<>();

            while (resultSet.next()) {
                JSONObject jsonObj = new JSONObject();

                // 遍历每一列
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnLabel(i);
                    Object value = resultSet.getObject(columnName);
                    jsonObj.put(columnName, value);

                }
                list.add(JSON.parseObject(jsonObj.toJSONString(), VehSafeAlarmDataBO.class));
            }
            resultSet.close();
            statement.close();

            String count64SQL = "select count(1) from db2.t_cmd0200_64 a join db1.anbiao_vehicle b on a.VehID = b.id left join db1.blade_dept dept64 on b.dept_id=dept64.id";
            statement = calciteConnection.prepareStatement(count64SQL);
            resultSet = statement.executeQuery();
            Integer total = 0;
            Integer total64 = 0;
            Integer total65 = 0;
            if (resultSet.next()) {
                total64 = resultSet.getInt(1);
            }
            resultSet.close();
            statement.close();


            String count65SQL = "select count(1) from db2.t_cmd0200_65 a join db1.anbiao_vehicle b on a.VehID = b.id left join db1.blade_dept dept64 on b.dept_id=dept64.id";
            statement = calciteConnection.prepareStatement(count65SQL);
            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                total65 = resultSet.getInt(1);
            }
            resultSet.close();
            statement.close();

            total = total64 + total65;

            calciteConnection.close();
            connection.close();
            return new ResponseMsg<>(200, "success", new PageData<>(total, list));
        } catch (Exception e) {
            try {
                if (calciteConnection != null && !calciteConnection.isClosed()) {
                    calciteConnection.close();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            return new ResponseMsg<>(201, e.getMessage());
        }


    }

    @Autowired
    private GzyjDaoluyunshuGpsMapper gzyjDaoluyunshuGpsMapper;


    @ApiOperation(value = "获取车辆里程数据", notes = "获取车辆里程数据")
    @PostMapping(value = "getLc")
    public ResponseMsg<List<VehLc>> getLc(VehLCParam param) {
        QueryWrapper<GzyjDaoluyunshuGps> w = new QueryWrapper<>();

        w.select("DATE_FORMAT( gpstime, '%Y-%m-%d' ) AS lcday", "sum( distFromPrePoint ) as lc")
                .eq("vehicleId", param.getVehId())
                .between("gpstime", param.getStartTime(), param.getEndTime())
                .groupBy("DATE_FORMAT( gpstime, '%Y-%m-%d' )")
                .orderByAsc("lcday");

        List<Map<String, Object>> list = gzyjDaoluyunshuGpsMapper.selectMaps(w);

        List<VehLc> data = list.stream().map(e -> new VehLc(String.valueOf(e.get("lcday")), Double.valueOf(String.valueOf(e.getOrDefault("lc", 0))))).collect(Collectors.toList());
        return new ResponseMsg<>(200, "success", data);
    }

    @ApiOperation(value = "获取车辆里程数据", notes = "获取车辆里程数据")
    @PostMapping(value = "getHistory")
    public ResponseMsg<List<GzyjDaoluyunshuGps>> getHistory(VehLCParam param) {
        QueryWrapper<GzyjDaoluyunshuGps> w = new QueryWrapper<>();
        w.eq("vehicleId", param.getVehId()).between("gpstime", param.getStartTime(), param.getEndTime()).orderByAsc("gpstime");

        List<GzyjDaoluyunshuGps> list = gzyjDaoluyunshuGpsMapper.selectList(w);

        return new ResponseMsg<>(200, "success", list);
    }

    @Autowired
    private GzyjStopHistoryMapper gzyjStopHistoryMapper;

    @ApiOperation(value = "获取停车历史", notes = "获取停车历史")
    @PostMapping(value = "getStopHistory")
    public ResponseMsg<List<GzyjStopHistory>> getStopHistory(VehLCParam param) {
        QueryWrapper<GzyjStopHistory> w = new QueryWrapper<>();
        w.eq("vehId", param.getVehId()).between("stopTime", param.getStartTime(), param.getEndTime()).orderByAsc("stopTime");

        List<GzyjStopHistory> list = gzyjStopHistoryMapper.selectList(w);

        return new ResponseMsg<>(200, "success", list);
    }


    @Value("${kafka.queue.down}")
    private String queueDown;

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    public String generateVerificationCode() {
        Random random = new Random();
        // 首位数字范围1-9
        int firstDigit = random.nextInt(9) + 1;
        // 剩余位数字范围0-9
        StringBuilder sb = new StringBuilder().append(firstDigit);
        for (int i = 0; i < 3; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }


    public String getAlarmNoteExt(Long value) {
        StringBuffer result = new StringBuffer();
        String binary = new StringBuffer(IntUtils.longToBinary(value, 64)).reverse().toString();

        if (binary.charAt(0) == '1') {
            result.append("紧急报警").append(",");
        }
        if (binary.charAt(1) == '1') {
            result.append("超速报警").append(",");
        }

        if (binary.charAt(2) == '1') {
            result.append("疲劳驾驶").append(",");
        }

        if (binary.charAt(3) == '1') {
            result.append("危险预警").append(",");
        }
        if (binary.charAt(4) == '1') {
            result.append("GNSS模块发生故障").append(",");
        }

        if (binary.charAt(5) == '1') {
            result.append("GNSS天线未接或被剪断").append(",");
        }
        if (binary.charAt(6) == '1') {
            result.append("GNSS天线短路").append(",");
        }

        if (binary.charAt(7) == '1') {
            result.append("终端主电源欠压").append(",");
        }
        if (binary.charAt(8) == '1') {
            result.append("终端主电源掉电").append(",");
        }

        if (binary.charAt(9) == '1') {
            result.append("终端LCD或显示器故障").append(",");
        }

        if (binary.charAt(10) == '1') {
            result.append("TTS模块故障").append(",");
        }

        if (binary.charAt(11) == '1') {
            result.append("摄像头故障").append(",");
        }


        if (binary.charAt(12) == '1') {
            result.append("道路运输证IC卡模块故障").append(",");
        }

        if (binary.charAt(13) == '1') {
            result.append("超速预警").append(",");
        }

        if (binary.charAt(14) == '1') {
            result.append("疲劳驾驶预警").append(",");
        }

        if (binary.charAt(15) == '1') {
            result.append("违规行驶报警").append(",");
        }

        if (binary.charAt(16) == '1') {
            result.append("胎压异常报警").append(",");
        }

        if (binary.charAt(17) == '1') {
            result.append("车道偏离报警").append(",");
        }


        if (binary.charAt(18) == '1') {
            result.append("当天累计驾驶超时").append(",");
        }

        if (binary.charAt(19) == '1') {
            result.append("超时停车").append(",");
        }

        if (binary.charAt(20) == '1') {
            result.append("进出区域").append(",");
        }

        if (binary.charAt(21) == '1') {
            result.append("进出路线").append(",");
        }

        if (binary.charAt(22) == '1') {
            result.append("路段行驶时间不足/过长").append(",");
        }

        if (binary.charAt(23) == '1') {
            result.append("路线偏离报警").append(",");
        }

        if (binary.charAt(24) == '1') {
            result.append("车辆VSS故障").append(",");
        }

        if (binary.charAt(25) == '1') {
            result.append("车辆油量异常").append(",");
        }

        if (binary.charAt(26) == '1') {
            result.append("车辆被盗").append(",");
        }

        if (binary.charAt(27) == '1') {
            result.append("车辆非法点火").append(",");
        }

        if (binary.charAt(28) == '1') {
            result.append("车辆非法位移").append(",");
        }


        if (binary.charAt(29) == '1') {
            result.append("碰撞预警").append(",");
        }

        if (binary.charAt(30) == '1') {
            result.append("侧翻预警").append(",");
        }

        if (binary.charAt(31) == '1') {
            result.append("非法开门报警").append(",");
        }

        if (binary.charAt(32) == '1') {
            result.append("视频信号丢失报警").append(",");
        }

        if (binary.charAt(33) == '1') {
            result.append("视频信号遮挡报警").append(",");
        }

        if (binary.charAt(34) == '1') {
            result.append("存储单元故障报警").append(",");
        }
        if (binary.charAt(35) == '1') {
            result.append("其他视频设备故障报警").append(",");
        }
        if (binary.charAt(36) == '1') {
            result.append("客车超员报警").append(",");
        }
        if (binary.charAt(37) == '1') {
            result.append("异常驾驶行为报警").append(",");
        }
        if (binary.charAt(38) == '1') {
            result.append("特殊报警录像达到存储阈值报警").append(",");
        }


        if (result.length() > 0) {
            result.deleteCharAt(result.lastIndexOf(","));
        }

        return result.toString();
    }


    @ApiOperation(value = "视频回放", notes = "视频回放")
    @PostMapping(value = "video/playback")
    public ResponseMsg<Object> videoPlayBack(VehVideoPlayBackParam vehVideoPlayBackParam) {
        if (vehVideoPlayBackParam.getStorageType() == 1) {
            Integer verifyCode = Integer.valueOf(generateVerificationCode());
            JSONObject param = new JSONObject();
            param.put("cmdID", 0x9205);
            param.put("ipAddress", vehVideoPlayBackParam.getSimNo());
            param.put("channel", vehVideoPlayBackParam.getChannelNo());
            param.put("storageType", Byte.valueOf("0"));
            param.put("bitstreamType", Byte.valueOf("0"));
            param.put("resourceType", Byte.valueOf("0"));
            param.put("alarm", vehVideoPlayBackParam.getAlarm());

            param.put("seq", verifyCode);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            param.put("beginTime", vehVideoPlayBackParam.getStartTime());
            param.put("endTime", vehVideoPlayBackParam.getEndTime());
            param.put("sendTime", sdf.format(new Date()));

            kafkaTemplate.send(queueDown, JSON.toJSONString(param, SerializerFeature.DisableCircularReferenceDetect));

            System.out.println("验证码：" + verifyCode);
            return new ResponseMsg<>(200, "success", String.valueOf(verifyCode));
        } else if (vehVideoPlayBackParam.getStorageType() == 2) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<GzyjVideoHistory> list = gzyjVideoHistoryMapper.selectList(new QueryWrapper<GzyjVideoHistory>().eq("simNo", vehVideoPlayBackParam.getSimNo())
                            .ge("beginTime", vehVideoPlayBackParam.getStartTime())
                            .le("endTime", vehVideoPlayBackParam.getEndTime())
                            .orderByAsc("beginTime")).stream()
                    .map(e -> {
                        e.setAlarmTxt(getAlarmNoteExt(e.getAlarmFlag()));
                        e.setBeginTimeStr(sdf.format(e.getBeginTime()));
                        e.setEndTimeStr(sdf.format(e.getEndTime()));
                        return e;
                    }).collect(Collectors.toList());
            return new ResponseMsg<>(200, "success", list);
        }
        return new ResponseMsg<>(200, "success");
    }


    @Autowired
    RedisTemplate<String, Object> clusterRedisTemplate;

    @Value("${redis.key.vehicle.cmdrs}")
    private String VehicleZdCMDRS;

    @Autowired
    private GzyjVideoHistoryMapper gzyjVideoHistoryMapper;

    @ApiOperation(value = "视频回放获取终端结果", notes = "视频回放获取终端结果")
    @PostMapping(value = "video/playback/getresult")
    public ResponseMsg<List<GzyjVideoHistory>> videoPlayBackGetResult(VehVideoPlayBackGetRSParam vehVideoPlayBackGetRSParam) {
        Object obj = clusterRedisTemplate.opsForValue().get(VehicleZdCMDRS + vehVideoPlayBackGetRSParam.getSimNo() + ":" + vehVideoPlayBackGetRSParam.getVerifyCode());
        Boolean rs= clusterRedisTemplate.hasKey(VehicleZdCMDRS + vehVideoPlayBackGetRSParam.getSimNo() + ":" + vehVideoPlayBackGetRSParam.getVerifyCode());
        if (rs) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect));

            JSONArray array = jsonObject.getJSONArray("aVResouces");

            if (array.size() == 0) {
                return new ResponseMsg<>(200, "终端不存在该时间段的视频", new ArrayList<>());
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                List<GzyjVideoHistory> list = gzyjVideoHistoryMapper.selectList(new QueryWrapper<GzyjVideoHistory>().eq("simNo", vehVideoPlayBackGetRSParam.getSimNo())
                        .ge("beginTime", vehVideoPlayBackGetRSParam.getStartTime())
                        .le("endTime", vehVideoPlayBackGetRSParam.getEndTime())
                        .orderByAsc("beginTime")).stream().map(e -> {
                    e.setAlarmTxt(getAlarmNoteExt(e.getAlarmFlag()));
                    e.setBeginTimeStr(sdf.format(e.getBeginTime()));
                    e.setEndTimeStr(sdf.format(e.getEndTime()));
                    return e;
                }).collect(Collectors.toList());
                return new ResponseMsg<>(200,"success", list);
            }

        } else {
            return new ResponseMsg<>(201, "终端未响应");
        }
    }


}
